<template>
  <div class="product-detail">
    <!-- Back button -->
    <div class="back-button">
      <button @click="goBack()">
        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
          stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"
          class="lucide lucide-chevron-left">
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner">
        <div class="spinner-ring"></div>
        <div class="loading-text">加载中...</div>
      </div>
    </div>

    <!-- Product Content -->
    <template v-else>
      <!-- Product image section -->
      <div class="product-image">
        <ImageCarousel :slides="productImages" :autoplay="true" :autoplay-interval="4000" :loop="true"
          @slide-change="handleSlideChange" />
      </div>
      <!-- Product info section -->
      <div class="product-info" v-if="productDetail">
        <div class="cat-options">
          <div class="option-item" v-for="(option, index) in petProduct.variants" :key="index">
            <img :src="option.imageUrl" :alt="option.name" class="option-img" />
            <span>{{ petProduct?.name }}</span>
          </div>
          <div class="more-options">
            <span @click="openModal">{{ petProduct.variants.length }}款可选 ›</span>
          </div>
        </div>

        <!-- Plus member section -->
        <div class="plus-section">
          <div class="plus-content">
            <span class="crown-icon">👑</span>
            <span class="plus-text">PLUS额外省50元</span>
          </div>
          <div class="plus-action">立享优惠 ›</div>
        </div>
        <!-- Description section -->
        <div class="info-section">
          <div class="section-content">
            <h2 class="product-name">{{ productDetail.name }}</h2>
            <p class="product-description">{{ productDetail.description }}</p>

            <div class="service-info">
              <div class="service-tag">
                <span>不支持退换</span>
              </div>
              <div class="service-tag guarantee">
                <span>7天价保</span>
                <span class="info-icon">ⓘ</span>
              </div>
            </div>
          </div>
          <div class="badge">排行榜 宠物猫热卖榜·第1名</div>
        </div>

        <!-- Product model selection section 未更改-->
        <div class="info-section">
          <div class="product-card">
            <div class="delivery" @click="selectAddress">
              <span>配送：</span>预计明天（3月31日）24:00前发货
              <button>></button>
              <!-- 待完成4.3 -->
              <div class="address">
                <span v-if="addresssList && addresssList.length > 0">
                  {{ addresssList[0].address }}
                </span>
                <span v-else>
                  还没有配送地址，点击添加
                </span>
              </div>
            </div>

            <div class="service">❌ 不支持7天无理由退货</div>
            <div class="activity">
              <span class="no-deposit">无门槛立减金</span>
              <span class="discount">80元立减金</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Bottom price and action bar -->
      <div class="action-bar">
        <div class="price-container">
          <div class="price-label">总价格</div>
          <div class="price-value">¥ {{ totalPrice }}</div>
        </div>
        <div class="action-buttons">
          <button class="add-to-cart-btn" @click="addToCart">加入购物车</button>
          <button class="buy-now-btn" @click="buyNow">购买</button>
        </div>
      </div>
    </template>
  </div>

  <PetProductModal :isOpen="isModalOpen" :product="petProduct" @close="closeModal" :showAddToCart="isShowCart"
    :showBuyNow="isShowBuyNow" @add-to-cart="handleAddToCart" :address="addresssList[0]" />
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProductDetail } from '@/views/productDetail/api/index'
import ImageCarousel from './components/ImageCarousel.vue'
import PetProductModal from './components/PetProductModal.vue'
import { getProductList, addProductToCart } from '@/views/productList/api/index'
import { useUserStore } from '@/stores/user';
import { getAddressList } from '@/views/address/api/index'
import { showToast } from 'vant';
defineOptions({
  name: 'ProductDetail',
})
const userStore = useUserStore();
const route = useRoute()
const router = useRouter()
const goBack = () => {
  router.go(-1)
}

const productDetail = ref(null)
const productImages = ref([])

//modal stats
const isShowCart = ref(true)
const isShowBuyNow = ref(true)

const handleAddToCart = (cartData) => {
  console.log(cartData.product.id, cartData.quantity)
  addProductToCart(userStore.userInfo.id, cartData.product.id, cartData.quantity)
}

// Selected options
const quantity = ref(1)

// Computed properties
const totalPrice = computed(() => {
  return (petProduct.value.price * quantity.value).toFixed(2)
})


const isModalOpen = ref(false)
const openModal = () => {
  if (!userStore.token) {
    showToast('请先登录');
    return;
  }
  isModalOpen.value = true
  isShowCart.value = true
  isShowBuyNow.value = true
}

const closeModal = () => {
  isModalOpen.value = false
}

const addToCart = () => {
  if (!userStore.token) {
    showToast('请先登录');
    return;
  }
  isModalOpen.value = true
  isShowBuyNow.value = false
  isShowCart.value = true
}

const buyNow = () => {
  if (!userStore.token) {
    showToast('请先登录');
    return;
  }
  isModalOpen.value = true
  isShowCart.value = false
  isShowBuyNow.value = true
}



const selectAddress = () => {
  if (!userStore.token) {
    showToast('请先登录');
    return;
  }
  // 跳转到地址选择页面时携带订单信息
  router.push({
    path: '/address',
    query: {
      addressIdInfo: JSON.stringify('no back data')
    }
  })
}




let productImages2
const petProduct = ref({
  id: '',
  name: '纯种英短猫',
  category: '宠物级别(6)',
  price: '9999',
  installment: '3期免息',
  mainImage: '',
  variants: [],
  productId: '',
})

const addresssList = ref([])



// 在 script setup 部分添加 loading 状态
const loading = ref(true)

// 修改 onMounted 钩子
onMounted(async () => {
  try {
    loading.value = true
    const res = await getProductDetail(route.params.id)
    const res2 = await getProductList(res.data.data.classifyId)
    const res3 = await getAddressList()

    if (res.data.code === 200) {
      productDetail.value = res.data.data
      productImages2 = ref([
        Object.values(productDetail.value.imageUrls).map((url) => ({
          image: url,
          alt: 'cat',
        })),
      ])
      productImages.value = [...productImages2.value[0]]
      petProduct.value.variants = res2.data.data
      petProduct.value.mainImage = productImages2.value[0][0].image
      petProduct.value.price = productDetail.value.price
      petProduct.value.id = productDetail.value.id
      petProduct.value.productId = productDetail.value.classifyId
    }
    if (res3.data.code === 200) {
      addresssList.value = res3.data.data
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
  } finally {
    loading.value = false
    nextTick(() => {
      const catOptions = document.querySelector('.cat-options')
      if (catOptions) {
        catOptions.style.gridTemplateColumns = `repeat(${petProduct.value.variants.length}, minmax(auto, 1fr))`
      }
    })
  }
})
const handleSlideChange = (index) => {

}
// const res = await getProductList(route.params.id)
//   if (res.data.code === 200) {
//     products.value = res.data.data
//   }


</script>

<style lang="scss" scoped>
@use 'sass:color';
// Theme color
$theme-color: #845ef5;
$background-color: #f0f0f0;
$white: #ffffff;
$gray: #cccccc;
$light-gray: #e0e0e0;
$dark-gray: #333333;

$primary-color: #ff4d4f;
$secondary-color: #f8f8f8;
$button-color: #ff6f61;
$text-color: #333;

.product-detail {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: $background-color;
  font-family: 'Arial', sans-serif;
  position: relative;
}

.back-button {
  position: fixed;
  top: 10px;
  left: 10px;
  z-index: 10;

  button {
    background-color: rgba(255, 255, 255, 0.7);
    border: none;
    border-radius: 50%;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;

    &:hover {
      background-color: $white;
    }
  }
}

.product-image {
  width: 100%;
  height: 300px;
  background-color: $gray;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;

  .image-placeholder {
    color: $dark-gray;
    font-size: 16px;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .image-indicators {
    position: absolute;
    bottom: 15px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: center;
    gap: 8px;

    span {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background-color: rgba(255, 255, 255, 0.5);

      &.active {
        background-color: $white;
        width: 10px;
        height: 10px;
      }
    }
  }
}

.product-info {
  flex: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  gap: 1px;
  background: #ffffff;
  border-radius: 20px;
  position: absolute;
  top: 284px;
  left: 0;
  right: 0;
  padding-bottom: 80px;

  .info-section {
    background-color: $white;
    border-radius: 8px;

    .section-title {
      font-size: 16px;
      color: $dark-gray;
      margin-bottom: 10px;
    }

    .section-content {
      margin: 5px 0;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
      padding: 10px;

      .product-name {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 10px;
        color: $dark-gray;
      }

      .product-description {
        font-size: 14px;
        line-height: 1.5;
        color: color.adjust($dark-gray, $lightness: 20%);
      }

      .option-group {
        margin-bottom: 15px;

        .option-label {
          font-size: 14px;
          color: color.adjust($dark-gray, $lightness: 20%);

          margin-bottom: 8px;
        }
      }
    }
  }
}

.quantity-selector {
  display: flex;
  align-items: center;
  width: fit-content;

  button {
    width: 30px;
    height: 30px;
    background-color: $white;
    border: 1px solid $light-gray;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 16px;

    &:first-child {
      border-radius: 4px 0 0 4px;
    }

    &:last-child {
      border-radius: 0 4px 4px 0;
    }

    &:disabled {
      color: $light-gray;
      cursor: not-allowed;
    }
  }

  span {
    width: 40px;
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid $light-gray;
    border-bottom: 1px solid $light-gray;
    font-size: 14px;
  }
}

.action-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: $white;
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 10;

  .price-container {
    display: flex;
    align-items: baseline;

    .price-label {
      font-size: 14px;
      color: $dark-gray;
      margin-right: 5px;
    }

    .price-value {
      font-size: 18px;
      font-weight: bold;
      color: $dark-gray;
    }
  }

  .action-buttons {
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border-radius: 4px;
      border: none;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s ease;

      &.add-to-cart-btn {
        background-color: rgba($theme-color, 0.1);
        color: $theme-color;

        &:hover {
          background-color: rgba($theme-color, 0.2);
        }
      }

      &.buy-now-btn {
        background-color: $theme-color;
        color: $white;

        &:hover {
          background-color: color.adjust($theme-color, $lightness: -5%);
        }
      }
    }
  }
}

// Responsive adjustments
@media (min-width: 768px) {
  .product-image {
    height: 400px;
  }

  .action-buttons {
    button {
      padding: 10px 20px;
      font-size: 16px;
    }
  }
}

.plus-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff9e6;
  padding: 10px 15px;
  border-radius: 10px;

  .plus-content {
    display: flex;
    align-items: center;

    .crown-icon {
      margin-right: 5px;
    }

    .plus-text {
      font-size: 14px;
      color: #333;
    }
  }

  .plus-action {
    color: #333;
    font-size: 14px;
  }
}

.service-info {
  margin: 5px 0;
  background-color: white;
  display: flex;

  .service-tag {
    background-color: #fceecd;
    color: #967544;
    font-size: 12px;
    padding: 2px 8px;
    border-radius: 2px;
    margin-right: 10px;
    display: flex;
    align-items: center;

    .info-icon {
      margin-left: 4px;
      font-size: 14px;
    }
  }

  .guarantee {
    color: #f0b90b;
  }
}

// Cat options
.cat-options {
  margin-top: 10px;
  background-color: white;
  padding: 10px 15px;
  display: grid;
  //3.30待完成，怎么动态相应个数
  grid-template-columns: repeat(3, 1fr);
  overflow-x: auto;
  width: 80%;
  height: 50px;
  gap: 10px;
  margin-top: -10px;

  &::-webkit-scrollbar {
    display: none;
    /* 隐藏滚动条，但保留滚动功能 */
  }

  .option-item {
    display: inline-flex;
    /* 改为 inline-flex */
    flex-direction: row;
    align-items: center;
    border-radius: 30px;
    background: #ebebeb;

    .option-img {
      margin: 0px 4px;
      width: 25px;
      height: 25px;
      border-radius: 50%;
      object-fit: cover;
      border: 1px solid #eee;
    }

    span {
      margin: 0 5px;
      font-size: 15px;
      color: #666;
      white-space: nowrap;
    }
  }

  .more-options {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 12px;
    position: absolute;
    right: 25px;
  }
}

.product-card {
  border-radius: 10px;
  background: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  font-family: Arial, sans-serif;
  padding: 10px;
  margin-top: 10px;
}

.badge {
  background: $primary-color;
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
}

.delivery {
  margin-top: 10px;
  font-size: 14px;
  color: $text-color;

  .address {
    font-size: 12px;
    color: gray;
  }

  button {
    background-color: transparent;
    border: none;
    position: absolute;
    right: 50px;
  }
}

.service {
  margin-top: 10px;
  font-size: 14px;
  color: rgb(167, 167, 167);
}

.activity {
  margin-top: 10px;
  font-size: 14px;
  color: $primary-color;
}

.actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;

  button {
    flex: 1;
    padding: 10px;
    border: none;
    border-radius: 5px;
    color: white;
    cursor: pointer;
    font-size: 14px;
  }

  .cart {
    background: #ffa726;
  }

  .buy {
    background: $button-color;
  }
}

// Loading Animation
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: $background-color;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.spinner-ring {
  width: 40px;
  height: 40px;
  border: 3px solid $light-gray;
  border-top-color: $theme-color;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: $dark-gray;
  font-size: 14px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
